using System;
using System.IO;
using System.Collections.Generic;

namespace Dida.Dxml
{
	public class ExternalFileLoader : IExternalsLoader
	{
		Stack<string> directoryStack = new Stack<string>();

		public ExternalFileLoader(string curDir)
		{
			directoryStack.Push(curDir);
		}

		public IExternalStream BeginStreamBlock(string name,XmlPositionMarker errorPos)
		{
			try
			{
				ExternalFile ret = new ExternalFile(name,directoryStack.Peek(),errorPos);
				
				FileInfo fileInfo = new FileInfo(name);
				directoryStack.Push(fileInfo.DirectoryName);

				return ret;
			}
			catch (Exception err)
			{
				throw new XmlReaderException(err, errorPos);
			}
		}

		public void EndStreamBlock(IExternalStream s)
		{
			directoryStack.Pop();
		}

		private class ExternalFile : IExternalStream
		{
			string fileName;
			string dir;
			XmlPositionMarker errorPos;

			public ExternalFile(string fileName,string dir,XmlPositionMarker errorPos)
			{
				this.fileName = fileName;
				this.dir = dir;
				this.errorPos = errorPos;
			}

			public Stream OpenStream()
			{
				try
				{
					string dirBackup = Directory.GetCurrentDirectory();
					Directory.SetCurrentDirectory(dir);

					FileStream ret = new FileStream(fileName, FileMode.Open, FileAccess.Read);

					Directory.SetCurrentDirectory(dirBackup);

					return ret;
				}
				catch (Exception err)
				{
					throw new XmlReaderException(err, errorPos);
				}
			}
		}
	}	
}